<template>
  <div>
    <div class="card" style="margin-bottom: 10px">
      <el-input placeholder="请输入患者姓名查询" style="width: 200px" v-model="data.patientName"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load()">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="card">

      <el-table :data="data.tableData" strip @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="patientName" label="患者姓名" fixed></el-table-column>
        <el-table-column prop="id" label="就诊单ID" width="85"></el-table-column>
        <el-table-column prop="patientId" label="患者ID"></el-table-column>
        <el-table-column prop="registrationId" label="挂号单ID" width="120"></el-table-column>
        <el-table-column prop="hospitalized" label="是否住院" >
          <template v-slot="scope">
            <el-tag
                :type="getStatusTagType(scope.row.hospitalized)"
                disable-transitions
            >
              {{ scope.row.hospitalized }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hospitalizationId" label="住院单ID" width="120"></el-table-column>
        <el-table-column prop="prescribedMedicine" label="是否开药" >
          <template v-slot="scope">
            <el-tag
                :type="getStatusTagType(scope.row.prescribedMedicine)"
                disable-transitions
            >
              {{ scope.row.prescribedMedicine }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="prescriptionId" label="药单ID" width="120"></el-table-column>
        <el-table-column prop="diagnosis" label="诊断信息" width="180"  show-overflow-tooltip></el-table-column>
        <el-table-column prop="treatmentPlan" label="治疗方案" width="180"  show-overflow-tooltip></el-table-column>
        <el-table-column prop="medicalAdvice" label="医嘱" width="180"  show-overflow-tooltip></el-table-column>
        <el-table-column prop="createdTime" label="叫号时间" width="180"></el-table-column>
        <el-table-column prop="endTime" label="结束就诊时间" width="180"></el-table-column>
        <el-table-column label="操作" align="center" width="410" fixed="right">
          <template v-slot="scope">
            <el-button size="mini" type="primary" plain @click="doctorAdvice(scope.row)">填写医嘱</el-button>
            <el-button size="mini" type="info" plain @click="reportAdmission(scope.row)"
                       v-if="scope.row.hospitalized !== '是'">上报住院请求</el-button>
            <el-button size="mini" type="warning" plain @click="createPrescription(scope.row)"
                       v-if="scope.row.prescribedMedicine !== '是'">开药
            </el-button>
            <el-button size="mini" type="danger" plain @click="finishVisit(scope.row)"
                       v-if="scope.row.endTime === null">结束就诊
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            style="margin-top: 5px"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="data.pageNum"
            :page-sizes="[3, 5, 10, 15, 20]"
            :page-size="data.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total">
        </el-pagination>
      </div>
    </div>

    <!-- New Admission Info Dialog -->
    <el-dialog title="信息" width="40%" v-model="data.admissionFormVisible" :close-on-click-modal="false"
               destroy-on-close>
      <el-form :model="data.admissionForm" label-width="100px" style="padding-right: 50px">
        <el-form-item label="患者ID" prop="patientId">
          <el-input v-model="data.admissionForm.patientId" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="入院日期" prop="admissionDate">
          <el-date-picker
              v-model="data.admissionForm.admissionDate"
              type="date"
              placeholder="选择入院日期"
              style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="出院日期" prop="dischargeDate">
          <el-date-picker
              v-model="data.admissionForm.dischargeDate"
              type="date"
              placeholder="选择出院日期"
              style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="科室ID" prop="departmentId">
          <el-input v-model="data.admissionForm.departmentId" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="床位号" prop="bedNumber">
          <el-input v-model="data.admissionForm.bedNumber" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="住院原因" prop="admissionReason">
          <el-input v-model="data.admissionForm.admissionReason" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.admissionFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveAdmission">保 存</el-button>
        </span>
      </template>
    </el-dialog>


    <el-dialog title="诊断结果" width="80%" v-model="data.doctorAdvice" :close-on-click-modal="false" destroy-on-close>
      <el-form-item label="诊断信息" prop="diagnosis">
        <el-input v-model="data.form.diagnosis" type="textarea" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="治疗方案" prop="treatmentPlan">
        <el-input v-model="data.form.treatmentPlan" type="textarea" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="医嘱" prop="diagnosis" >
        <el-input v-model="data.form.medicalAdvice" type="textarea" autocomplete="off"/>
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.doctorAdvice = false, load()">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
import request from '@/utils/request'
import {ElMessage} from 'element-plus'
// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'

// 定义响应式数据
const data = reactive({
  tableData: [],  // 表格数据
  pageNum: 1,     // 当前页码
  pageSize: 10,   // 每页显示数量
  total: 0,       // 总记录数
  patientName: null,     // 搜索条件
  formVisible: false, // 表单显示状态
  admissionFormVisible: false, // 住院对话锁
  doctorAdvice: false, // 医嘱对话锁
  form: {},       // 表单数据
  admissionForm: {}, // 住院表单
  ids: [],        // 选中数据的ID
  user: JSON.parse(localStorage.getItem('system-user') || '{}'),
  currentPrescriptionId: null

})

// 分页查询
const load = () => {

  request.get('/PatientVisit/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      patientName: data.patientName,
      doctorId: data.user.id,
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list
      data.total = res.data?.total
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 医嘱
const doctorAdvice = (row) => {
  data.form = row;
  data.doctorAdvice = true;
}

// 保存数据
const save = () => {
  const url = data.form.id ? '/PatientVisit/update' : '/PatientVisit/add'
  const method = data.form.id ? 'PUT' : 'POST'
  request({
    url,
    method,
    data: data.form,
  }).then(res => {
    if (res.code === '200') {
      load();
      ElMessage.success('保存成功')
      data.formVisible = false;
      data.doctorAdvice = false;
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// Save admission information
const saveAdmission = () => {
  // 首先保存入院信息
  request({
    url: '/Admissions/add',
    method: 'POST',
    data: data.admissionForm,
  }).then(res => {
    if (res.code === '200') {
      // 入院信息保存成功，设置“是否住院”为“是”
      data.admissionForm.hospitalized = '是';
      data.admissionForm.hospitalizationId = data.admissionForm.id;
      // 更新患者就诊信息表
      const updateVisitParams = {
        ...data.admissionForm,
        hospitalized: '是', // 确保住院状态更新为“是”
        hospitalizationId: data.admissionForm.id,
      };

      request({
        url: '/PatientVisit/updateHospitalizedStatus',
        method: 'PUT',
        data: updateVisitParams,
      }).then(updateRes => {
        if (updateRes.code === '200') {
          load(); // 重新加载数据
          ElMessage.success('保存成功');
          data.admissionFormVisible = false;
        } else {
          ElMessage.error(updateRes.msg);
        }
      }).catch(() => {
        ElMessage.error('更新就诊信息失败');
      });
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(() => {
    ElMessage.error('保存入院信息失败');
  });
}


// 处理选中的行
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id)
}

// 重置筛选条件
const reset = () => {
  data.patientName = null
  load()
}

// 处理页码变化
const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum
  load(pageNum)
}
const handleSizeChange = (pageSize) => {
  data.pageSize = pageSize
  load()
}

// 页面初始化加载数据
load()

const finishVisit = (row) => {
  let params = JSON.parse(JSON.stringify(row))
  request.put('/PatientVisit/updateEndTime', params).then(res => {
    if (res.code === '200') {
      ElMessage.success('结束就诊成功！')
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 校验规则
const rules = {
  patientId: [
    {required: true, message: '患者ID不能为空', trigger: 'blur'}
  ],
  doctorId: [
    {required: true, message: '医生ID不能为空', trigger: 'blur'}
  ],
  registrationId: [
    {required: true, message: '挂号单ID不能为空', trigger: 'blur'}
  ]
}

// Use new dialog
const reportAdmission = (row) => {
  // Set data for the new dialog
  data.admissionForm = {...row, hospitalized: '是'}
  // Show the new dialog
  data.admissionFormVisible = true
}


//点击开药后的逻辑
const createPrescription = (row) => {
  console.log(row)
  // 创建药单记录，暂时只保存患者ID、医生ID和就诊单ID
  request.get('/prescription/addPrescription',
      {
        params: {
          patientId: row.patientId,
          doctorId: row.doctorId,
          visitId: row.id
        }
      }
  ).then(res => {
    if (res.code === '200') {
      console.log(res.data)
      // 保存药单ID，用于后续添加药品条目
      data.currentPrescriptionId = res.data.id;
      updateVisitForm(row)//更新就诊单信息
    } else {
      ElMessage.error('创建药单失败: ' + res.msg);
    }
  })
}

const updateVisitForm = (row) => {
  let param = JSON.parse(JSON.stringify(row))
  param.prescribedMedicine = '是'//设置“是否开药”为“是”
  param.prescriptionId = data.currentPrescriptionId//绑定药单ID
  console.log(param)
  request.put('/PatientVisit/update', param).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('创建药单成功！请点击“处理开药”菜单进行药品选择！')
    } else {
      ElMessage.error(res.msg)
    }
  })
}
// 根据挂号状态返回对应的标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '是':
      return 'success';
    case '否':
      return 'danger';
    default:
      return 'primary';
  }
};
</script>


<style scoped>

</style>